package com.butte.mound.frame.security;

import com.butte.mound.frame.token.BaseToken;
import com.butte.mound.frame.token.TokenContext;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

@Component
@Aspect
@RequiredArgsConstructor
public class AuthAop {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.butte.mound.frame.security.Auth)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around (ProceedingJoinPoint point) throws Throwable {
        try{
            // 检查权限
            checkAuth(point);
            // 执行方法
            Object result = point.proceed();
            return result;
        } catch (Exception e){
            e.printStackTrace();
            throw e ;
        }
    }

    private void checkAuth (ProceedingJoinPoint point){
        try{
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            Auth auth = method.getAnnotation(Auth.class);
            BaseToken token = TokenContext.getToken();
            token.checkPermission(auth.authCode());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}